var express = require('express');
var router = express.Router();
var sqlQuery = require('../../../module/sql');
var jiami = require('../../../module/jiami')

/* GET users listing. */
router.get('/', async(req, res, next)=>{
    let role = await getRole()
    let options = {role};
  res.render('admin/user/add',options)
});

//获取用户角色
async function getRole(){
    let sqlStr = 'select * from role'
    let result = await sqlQuery(sqlStr);
    //结果返回
    return Array.from(result);
  }


router.post('/',async(req,res)=>{

    let password = jiami(req.body.password)
    let email = req.body.email
    let phone = req.body.phone
    let roleid = req.body.roleid
    let username = req.body.username
    let state = req.body.state
    if(state == 'on'){
        state = 1
    }else{
        state = 0
    }
    let sqlStr = "insert into user (username,password,roleid,phone,email,state) values(?,?,?,?,?,?)"
    let arr = [username,jiami(password),roleid,phone,email,state]
    await sqlQuery(sqlStr,arr)
    res.json({
        state:"ok",
        content:"添加成功"
      })
})



//验证添加用户时用户名师傅已存在
router.post('/testing',async(req,res)=>{
    //判断用户名是否存在
    let username = req.body.username
    let sqlStr1 = "select * from user where username = ?"
    let result1 = await sqlQuery(sqlStr1,[username])
    if(result1.length == 0){
        res.json({
            state:"ok",
            content:"没有此用户名，可以添加"
        })
    }else{
        res.json({
            state:"fail",
            content:"用户名已存在"
        })
    }
})

module.exports = router;
